package com.kanesoft.android.gdx.widgets;

import java.util.Iterator;
import java.util.Vector;

import com.badlogic.gdx.Gdx;

public class WidgetEventsBroadcast {

    private Vector<GdxWidgets> listeners;

    private boolean screenWasTouched;

    /**
     * One Constructor for SCREEN.
     */
    public WidgetEventsBroadcast() {
        listeners = new Vector<GdxWidgets>();
    }

    /**
     * Call this method in Game.render() to publish touch events all over the
     * framework
     */
    public void updateEvents(float deltaTime, float camOffsX, float camOffsY) {
        if (Gdx.input.justTouched()) {
            screenWasTouched = true;
            broadcastOnPressDown(Gdx.input.getX(), Gdx.graphics.getHeight()
                    - Gdx.input.getY());
        }

        if ((screenWasTouched) && (Gdx.input.isTouched() == false)) {
            screenWasTouched = false;
            broadcastOnPressUp(Gdx.input.getX(), Gdx.graphics.getHeight()
                    - Gdx.input.getY());
        }
        
        notifyWidgetsToDraw(deltaTime, camOffsX, camOffsY);
    }

    /**
     * Used this method to register the widget to receive events
     * 
     * @param objectListening
     */
    public void addGdxWidget(GdxWidgets objectListening) {
        if (objectListening == null)
            return;

        listeners.add(objectListening);
    }
    
    /**
     * Use this method to de-register a widget
     * @param objectListening
     */
    public void removeGdxWidget(GdxWidgets objectListening) {
        if (objectListening == null)
            return;

        listeners.remove(objectListening);
    }

    private void notifyWidgetsToDraw(float deltaTime, float offsX, float offsY) {
        for (Iterator<GdxWidgets> i = listeners.iterator(); i.hasNext();) {
            GdxWidgets objectListening = i.next();
            objectListening.draw(deltaTime, offsX, offsY);
        }
    }
    
    private void broadcastOnPressDown(int x, int y) {

        for (Iterator<GdxWidgets> i = listeners.iterator(); i.hasNext();) {
            GdxWidgets objectListening = i.next();
            objectListening.onPressDown(x, y);
        }
    }

    private void broadcastOnPressUp(int x, int y) {

        for (Iterator<GdxWidgets> i = listeners.iterator(); i.hasNext();) {
            GdxWidgets objectListening = i.next();
            objectListening.onPressUp(x, y);
        }
    }

}
